package com.kinglone.back.pdf.service.impl;

import com.kinglone.back.pdf.dao.PdfMapper;
import com.kinglone.back.pdf.model.Pdfdto;
import com.kinglone.back.pdf.service.PdfService;
import com.kinglone.common.poi.MSWordTool;
import com.kinglone.common.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 *
 */
@Service("pdfService")
public class PdfServiceImpl implements PdfService {

    @Resource
    private PdfMapper pdfMapper;

    @Override
    public ResultMsg createpDF(Pdfdto pdfdto) {
        ResultMsg resultMsg = new ResultMsg();
        Map map=new HashMap();
        map.put("id",pdfdto.getId());
        //根据id获取设备数据，测试用
        List<Pdfdto> pdfdtoList = pdfMapper.getEqpListById(map);
        //根据id获取公共部分数据，测试用
        Pdfdto pdfTemp = pdfMapper.getPdfdtoById(map);
        //获取模板
        String basepath = PropertieUtil.getValue("config.properties", "upload_url");
        String templatePath = basepath + File.separator + "template"+File.separator +"test"+File.separator+"testtemp.docx";

        File templateFile = new File(templatePath);

        if(templateFile.exists()){
            //开始根据模板创建文件
            MSWordTool changer = new MSWordTool();
            changer.setTemplate(templatePath);

            //书签替换
            Map<String,String> content = new HashMap<String,String>();
            content.put("areaName",pdfTemp.getAreaname());
            changer.replaceBookMark(content);

            File pic = new File("E:\\test\\xiaosimm.png");
            try{
                FileInputStream is = new FileInputStream(pic);
              //  changer.addPictureData(is, XWPFDocument.PICTURE_TYPE_PNG);

            }catch(Exception e){
                e.printStackTrace();
            }



            Map<String, String> tableOne = new HashMap<String, String>();
            tableOne.put("workCod",pdfTemp.getWorkcod());
            tableOne.put("deptName",pdfTemp.getDeptname());
            String apprDate = pdfTemp.getCreatetime();
            System.out.println("apprDate:"+apprDate);
            String year = "";
            String month ="";
            String day ="";
            if(StringUtils.isNotEmpty(apprDate)){
                String [] str=apprDate.split("-");
                year = str[0];
                month=str[1];
                String dayTemp = str[2];
                day = dayTemp.substring(0, 2);
            }
            tableOne.put("year",year);
            tableOne.put("month",month);
            tableOne.put("day",day);
            changer.replaceTableBookMark(tableOne,"TableOne");


            //表格中文本的替换
            Map<String, String> tableMap = new HashMap<String, String>();
            tableMap.put("untName",pdfTemp.getUntname());
            tableMap.put("untAddr",pdfTemp.getUntaddr());

           // Double totalAmount = workLoadMainTemp.getIspAmount();
            String amount = pdfdtoList.get(0).getAmount();
            String totalAmountUP ="";
            if(StringUtils.isEmpty(amount)){
                totalAmountUP ="零圆整";
            }else{
                totalAmountUP = Moneyutil.toUppercase(amount);
            }

            int eqpNum = pdfdtoList.size();
            System.out.println(totalAmountUP);
            String strN = "此次共检设备 ";
            String strM = " 台（只、辆），合计人民币￥";
            tableMap.put("total",strN+eqpNum+strM+totalAmountUP);
            //采用拓展方法进行表格替换,变量自动加上${}对比
            changer.replaceTableBookMark(tableMap,"Table");

            //替换表格标签
            List<Map<String ,String>> content2 = new ArrayList<Map<String, String>>();
            for(int i = 0; i < pdfdtoList.size(); i++){
                Pdfdto pdf=pdfdtoList.get(i);
                Map<String, String> table1 = new HashMap<String, String>();
                table1.put("eqpName",pdf.getEqpname());
                table1.put("eqpMod",pdf.getEqpmod());
                table1.put("eqpNum",pdf.getEqpnum());
                table1.put("amount",pdf.getAmount());
                table1.put("linkName",pdf.getLinkname());
                table1.put("remark",pdf.getRemark());
                content2.add(table1);
            }
            changer.insertTableAtBookMark("WorkLoadList" ,content2);

            //保存替换后的WORD
            //保存word路径
            String relativePath =File.separator + "print"+File.separator +"testPdf"+File.separator+ DateUtils.format(new Date(), "yyyyMMdd")+File.separator;
            String fileSavePath = basepath + relativePath;
            System.out.println("完整存储路径："+fileSavePath);
            File f=new File(fileSavePath);
            if(!f.exists()){
                f.mkdirs();
            }
            String uuid= UUIDUtils.getUUID();
            String fileName=uuid+".docx";
            String path=fileSavePath + fileName;



            changer.saveAs(path);
            String previewPath=fileSavePath+uuid+".pdf";
            OpenOfficeUtil.docToPdf(path,previewPath);

            //生成pdf后保存路径
            /*String fromType ="workloadPrint";
            Map map=new HashMap<>();
            map.put("fromType",fromType);
            map.put("fromId",workMainId);
            map.put("updateMan", ShiroKit.getUser().getAccount());
            map.put("updateTime",DateUtil.getTime());
            basUploadFileMapper.delAplPrint(map);
            BasUploadFile file =new BasUploadFile();
            file.setFromType(fromType);
            file.setFromId(workMainId);
            file.setPath("img-pdf.png");//缩略图路径
            file.setFileName(uuid+".pdf");
            file.setRealName(uuid+".pdf");
            file.setRealFilePath(previewPath);
            file.setFileSuffix(".pdf");
            file.setUpdateMan(ShiroKit.getUser().getAccount());
            file.setUpdateTime(DateUtil.getTime());
            file.setType("pdf");
            file.setPreviewPath(previewPath);

            basUploadFileMapper.insert(file);*/
        }else{
            resultMsg.setSuccess(false);
            resultMsg.setMessage("pdf生成失败,模板文件不存在!");
            return resultMsg;
        }
        resultMsg.setSuccess(true);
        resultMsg.setMessage("pdf生成成功!");
        return resultMsg;
    }
}
